Passed
Push — master ( 94a8cd...8e610f )
by Dmytro
02:30 queued 11s
created

web.js ➔ checkBasicAuth   A

Complexity

Conditions 2

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 8
dl 0
loc 13
rs 10
c 0
b 0
f 0
1
import express from 'express';
2
import { createBullBoard } from '@bull-board/api';
3
import { BullAdapter } from '@bull-board/api/bullAdapter';
4
import { ExpressAdapter } from '@bull-board/express';
5
import packageInfo from '../package.json';
6
import logger from './logger';
7
8
import Queue from './Queue';
9
import config from './config';
10
11
const queues = [
12
    config.queue.repo,
13
    config.queue.main
14
].map(conf => Queue.createQuue({
15
    name  : conf.name,
16
    redis : config.queue.redis
17
}));
18
19
const serverAdapter = new ExpressAdapter();
20
21
createBullBoard({
22
    queues : queues.map(q => new BullAdapter(q)),
23
    serverAdapter
24
});
25
26
const app = express();
27
28
let server = null;
29
30
if (config.web.start) {
31
    server = app.listen(config.web.port, () => {
32
        const { port } = server.address();
33
34
        logger.info(`WEB STARTING AT PORT ${port}`);
35
    });
36
}
37
38
export default app;
39
40
export function onShutdown() {
41
    if (server) {
42
        return new Promise((res) => {
43
            server.close(res);
44
        });
45
    }
46
}
47
48
serverAdapter.setBasePath('/admin/bull');
49
const auth = { login: 'admin', password: config.web.admin.password };
50
51
function checkBasicAuth(req, res, next) {
52
    const b64auth = (req.headers.authorization || '').split(' ')[1] || '';
53
    const [ login, password ] = Buffer.from(b64auth, 'base64').toString().split(':');
54
55
    if (login === auth.login && password === auth.password) {
56
        return next();
57
    }
58
59
    const noAuthCode = 401;
60
61
    res.set('WWW-Authenticate', 'Basic realm="401"');
62
    res.status(noAuthCode).send('Authentication required');
63
}
64
65
function renderInfo(req, res) {
66
    res.send({
67
        name        : packageInfo.name,
68
        version     : packageInfo.version,
69
        description : packageInfo.description
70
    });
71
}
72
73
app.use('/admin/bull', checkBasicAuth, serverAdapter.getRouter());
74
app.use('/admin/info', checkBasicAuth, renderInfo);
75
76
function renderFile(file) {
77
    app.use(`/${file.fileName}`, (req, res) => {
78
        res.attachment(file.fileName);
79
        res.type('txt');
80
        res.send(file.content);
81
    });
82
}
83
84
config.verification?.forEach(verifyFile => renderFile(verifyFile));
85